﻿#define _CRT_SECURE_NO_WARNINGS 1

#include <stdio.h>
#include <stdlib.h>

enum { SIZE = 5 };
int main()
{
	double a[SIZE] = { 1.,2.,3.,4.,5. };
	//文件写操作
	FILE* fp = fopen("test.bin", "wb"); // 必须用二进制模式
	fwrite(a, sizeof *a, SIZE, fp); // 写 double 的数组
	fclose(fp);

	double b[SIZE];
	//文件读操作
	fp = fopen("test.bin", "rb");
	size_t ret_code = fread(b, sizeof *b, SIZE, fp); // 读 double 的数组

	//成功与失败的判定
	if (ret_code == SIZE) //读取成功个数与预设读取个数相同，则是读取成功
	{
		puts("Array read successfully, contents: ");
		for (int n = 0; n < SIZE; ++n)
			printf("%f ", b[n]);
		putchar('\n');
	}
	else //读取成功个数与预设读取个数不同，则是读取失败
	{ 
		if (feof(fp))//判断是否是遇到文件末尾
			printf("Error reading test.bin: unexpected end of file\n");
		else if (ferror(fp)) //若不是遇到文件末尾，判断流错误
		{
			perror("Error reading test.bin");
		}
	}
	fclose(fp);
}

int main6(void)
{
	int c; // 注意：int，非char，要求处理EOF（值为-1）
	FILE* fp = fopen("test.txt", "r");
	if (!fp) {
		perror("File opening failed");
		return EXIT_FAILURE;
	}

	//fgetc 当读取失败的时候或者遇到文件结束的时候，都会返回EOF
	while ((c = fgetc(fp)) != EOF) // 标准C I/O读取⽂件循环
	{
		putchar(c);
	}

	//判断是什么原因结束的
	if (ferror(fp))//ferror函数返回与流相关的非0错误码
		puts("I/O error when reading");
	else if (feof(fp))//判断是不是遇到了文件末尾，若是则则返回非0值
		puts("End of file reached successfully");
	fclose(fp);
}

int main5()
{
	int n;
	FILE* pFile;
	char buffer[27];

	pFile = fopen("myfile.txt", "w+");
	for (n = 'A'; n <= 'Z'; n++)
		fputc(n, pFile);
	rewind(pFile);

	fread(buffer, 1, 26, pFile);
	fclose(pFile);

	buffer[26] = '\0';
	printf(buffer);
	return 0;
}

int main4()
{
	FILE* pFile;
	long size;
	pFile = fopen("myfile.txt", "rb");
	if (pFile == NULL)
		perror("Error opening file");
	else
	{
		fseek(pFile, 0, SEEK_END); // non-portable
		size = ftell(pFile);
		fclose(pFile);
		printf("Size of myfile.txt: %ld bytes.\n", size);
	}
	return 0;
}

int main3()
{
	FILE* pFile;
	pFile = fopen("example.txt", "wb");
	fputs("This is an apple.", pFile);
	fseek(pFile, 9, SEEK_SET);
	fputs(" sam", pFile);
	fclose(pFile);

	return 0;
}

int main2()
{
	//打开文件
	FILE* pFile = fopen("myfile.txt", "w");

	//文件操作
	if (pFile != NULL)
	{
		fputs("fopen example", pFile);
		//关闭文件
		fclose(pFile);
		pFile = NULL;
	}
	return 0;
}

int main1()
{
	int a = 10000;
	FILE* pf = fopen("test.txt", "wb");
	fwrite(&a, 4, 1, pf);//⼆进制的形式写到⽂件中
	fclose(pf);
	pf = NULL;
	return 0;
}
